"""
题库系统 - API序列化器
"""
from rest_framework import serializers
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from .models import (
    Question, QuestionBank, QuestionBankItem, QuestionTag,
    QuestionTagRelation, QuestionUsageHistory
)

User = get_user_model()


class QuestionTagSerializer(serializers.ModelSerializer):
    """题目标签序列化器"""

    class Meta:
        model = QuestionTag
        fields = ['id', 'name', 'description', 'color', 'category', 'usage_count', 'created_at']


class QuestionListSerializer(serializers.ModelSerializer):
    """题目列表序列化器"""
    creator_name = serializers.CharField(source='creator.real_name', read_only=True)
    question_type_display = serializers.CharField(source='get_type_display', read_only=True)
    difficulty_display = serializers.CharField(source='get_difficulty_display', read_only=True)

    class Meta:
        model = Question
        fields = [
            'id', 'title', 'type', 'question_type_display', 'difficulty', 'difficulty_display',
            'points', 'subject', 'chapter', 'tags', 'creator', 'creator_name',
            'usage_count', 'correct_rate', 'created_at'
        ]
        read_only_fields = ['creator', 'usage_count', 'correct_rate', 'created_at']


class QuestionDetailSerializer(serializers.ModelSerializer):
    """题目详情序列化器"""
    creator_name = serializers.CharField(source='creator.real_name', read_only=True)
    question_type_display = serializers.CharField(source='get_type_display', read_only=True)
    difficulty_display = serializers.CharField(source='get_difficulty_display', read_only=True)
    status_display = serializers.CharField(source='get_status_display', read_only=True)
    review_status_display = serializers.CharField(source='get_review_status_display', read_only=True)

    class Meta:
        model = Question
        fields = [
            'id', 'title', 'stem', 'type', 'question_type_display', 'difficulty',
            'difficulty_display', 'points', 'options', 'answer', 'analysis',
            'explanation', 'subject', 'chapter', 'section', 'tags', 'keywords',
            'creator', 'creator_name', 'status', 'status_display', 'review_status',
            'review_status_display', 'reviewer', 'review_comment', 'reviewed_at',
            'usage_count', 'correct_rate', 'is_public', 'created_at', 'updated_at'
        ]
        read_only_fields = ['creator', 'reviewer', 'reviewed_at', 'usage_count',
                           'correct_rate', 'created_at', 'updated_at']


class QuestionCreateSerializer(serializers.ModelSerializer):
    """题目创建序列化器"""

    class Meta:
        model = Question
        fields = [
            'title', 'stem', 'type', 'difficulty', 'points', 'options', 'answer',
            'analysis', 'explanation', 'subject', 'chapter', 'section', 'tags',
            'keywords', 'is_public'
        ]

    def validate_options(self, value):
        """验证选项"""
        question_type = self.initial_data.get('type')
        if question_type in ['choice', 'multiple_choice']:
            if not value or not isinstance(value, list):
                raise ValidationError("选择题必须提供选项")
        return value

    def validate_answer(self, value):
        """验证答案"""
        question_type = self.initial_data.get('type')
        if question_type == 'true_false' and value not in [True, False]:
            raise ValidationError("判断题答案必须是True或False")
        return value


class QuestionUpdateSerializer(serializers.ModelSerializer):
    """题目更新序列化器"""

    class Meta:
        model = Question
        fields = [
            'title', 'stem', 'difficulty', 'points', 'options', 'answer',
            'analysis', 'explanation', 'tags', 'keywords', 'is_public'
        ]


class QuestionBankSerializer(serializers.ModelSerializer):
    """题库序列化器"""
    owner_name = serializers.CharField(source='owner.real_name', read_only=True)
    type_display = serializers.CharField(source='get_type_display', read_only=True)

    class Meta:
        model = QuestionBank
        fields = [
            'id', 'name', 'description', 'type', 'type_display', 'subject',
            'grade_level', 'difficulty_range', 'question_count', 'total_points',
            'owner', 'owner_name', 'is_public', 'allow_export', 'last_import_at',
            'created_at', 'updated_at'
        ]
        read_only_fields = ['owner', 'question_count', 'total_points', 'last_import_at']


class QuestionBankDetailSerializer(QuestionBankSerializer):
    """题库详情序列化器"""
    questions = QuestionListSerializer(source='active_questions', many=True, read_only=True)

    class Meta(QuestionBankSerializer.Meta):
        fields = QuestionBankSerializer.Meta.fields + ['questions']


class QuestionBankCreateSerializer(serializers.ModelSerializer):
    """题库创建序列化器"""

    class Meta:
        model = QuestionBank
        fields = ['name', 'description', 'type', 'subject', 'grade_level', 'difficulty_range', 'is_public']


class QuestionBankItemSerializer(serializers.ModelSerializer):
    """题库题目序列化器"""
    question_info = QuestionListSerializer(source='question', read_only=True)

    class Meta:
        model = QuestionBankItem
        fields = [
            'id', 'question_bank', 'question', 'question_info', 'custom_points',
            'custom_difficulty', 'status', 'order', 'added_at'
        ]
        read_only_fields = ['added_at']


class QuestionImportSerializer(serializers.Serializer):
    """题目导入序列化器"""
    file = serializers.FileField()
    question_bank_id = serializers.IntegerField()

    def validate_file(self, value):
        """验证文件格式"""
        allowed_extensions = ['.xlsx', '.xls', '.csv', '.json']
        file_extension = value.name.lower().split('.')[-1]
        if file_extension not in [ext[1:] for ext in allowed_extensions]:
            raise ValidationError(f"不支持的文件格式，支持的格式：{', '.join(allowed_extensions)}")
        return value


class QuestionExportSerializer(serializers.Serializer):
    """题目导出序列化器"""
    question_ids = serializers.ListField(child=serializers.IntegerField())
    format = serializers.ChoiceField(choices=['xlsx', 'csv', 'json'])
    include_answers = serializers.BooleanField(default=False)
    include_analysis = serializers.BooleanField(default=False)


class QuestionStatisticsSerializer(serializers.Serializer):
    """题目统计序列化器"""
    question_id = serializers.IntegerField()
    start_date = serializers.DateField(required=False)
    end_date = serializers.DateField(required=False)


class QuestionBankStatisticsSerializer(serializers.Serializer):
    """题库统计序列化器"""
    question_bank_id = serializers.IntegerField()
    start_date = serializers.DateField(required=False)
    end_date = serializers.DateField(required=False)